var ctx;
var doing = false;
function setCtx(ctx) {
    this.ctx = ctx;
}

var cartObj = {
	// 结算选择项
	settleSelect : function () {
		var total = 0;
		$(".one-item").each(function() {
            if($(this).prop('checked')) {
                var ss = $(this).attr('id').split('_');
                var price = ss[1];
                var num = ss[2];
                total += Number(price).mul(num);
            }
        });
        $('#totalPrice').html('￥' + total);
        $('#hiddenTotalPrice').val(total);
	},
	//勾选店铺
    toggleShopSelect: function(){
        var me = this;
    },
	toggleCheckbox : function(type, cb, el){
        if(type = 1) {
            $(el).prop('checked', cb);
        } else {
        	shopEl = el;
            shopList = el.parents('.shop').next();
            this.toggleSingle(type, flag, shopList);
            this.toggleShop(type, flag, shopEl); 
        }
    },
    updateCartAmount : function(before, cur, obj) {
        var ss =$(obj).attr("id").split("_");
        var me = this;
        var mEl = $('input[type=checkbox]', obj.closest('.one-order'));
        var sub = cur - before;
        var price = ss[3];
        $.post(ctx + "/shopcart/updateAmount", {
            id : ss[0],
            sub : sub,
            price : price,
            amount : cur,
        }, function(data) {
        	data = JSON.parse(data);
            if (data.success) {
                var beforeSub = $('#hiddenTotalPrice').val();
                var after = Number(beforeSub).add(Number(price).mul(sub));
                if(!$(mEl).prop('checked')){
                    after = Number(beforeSub).add(Number(price).mul(cur));
                }
                $('#totalPrice').html('￥' + after);
                $('#hiddenTotalPrice').val(after);
                $(obj).val(cur);
                
                // udpate checkbox id
                var preId = $(mEl).attr('id');
                preId = preId.substring(0, preId.lastIndexOf('_') + 1) + cur;
                $(mEl).attr('id',preId);
                me.toggleCheckbox(1, true, mEl);
            } else {
                layer.msg(data.msg, {
                    icon : 2,
                    time : 2000
                });
            }
            doing = false;
        });
    },
    initListener : function() {
        var me = this;
        $('.padd').delegate('a.increment', 'click', function(){
            if(doing) return;
            doing = true;

            var anode = $(this);
            var pnode = anode.parent();
            var inputEl = $('input', pnode);
            var cur = inputEl.val();
            var before = inputEl.val();
            cur++;
            me.updateCartAmount(before, cur, $(anode).prev());
        });

        $('.padd').delegate('a.decrement', 'click', function(){
            if(doing) return;
            var anode = $(this);
            if(anode.hasClass('disabled')){
                return;
            }
            doing = true;
            
            var pnode = anode.parent();
            var inputEl = $('input', pnode);
            var cur = inputEl.val();
            var before = inputEl.val();
            cur--;
            if(cur == 0){
                doing = false;
                return;
            }
            me.updateCartAmount(before, cur, $(anode).next());
        });

        //商品数量文本框获取焦点，保存之前的值
        $('.padd').delegate('div.amount input', 'focus', function(event){
            var val = parseInt($(this).val());
            if(isNaN(val)){
                return;
            }
            if(val){
                $("#changeBeforeValue").val(val);
                $("#changeBeforeId").val($(this).attr("id"));
            }
        });

        //改变商品数量
        $('.padd').delegate('div.amount input', 'change', function(event){
            if(doing) return;
            doing = true;
            me.updateCartAmount($("#changeBeforeValue").val(), $(this).val(), $(this));
        });
        
        // 去结算：普通
        $('.padd').delegate('.pay-btn', 'click', function(){
            var shopcartIds = '';
            $(".one-item").each(function() {
                if($(this).prop('checked')) {
                    shopcartIds += $(this).attr('id').split('_')[0] + ',';
                }
            });
            if(shopcartIds == ''){
                return;
            } else {
                location.href = ctx + "/shopcart/confirmOrder?shopcartIds=" + shopcartIds + "&type=1";
            }
        });
        
        // 勾选店铺
        $('.padd').delegate('input[name=checkShop]', 'click', function(){
            //点击复选框后所有复选框不可选
//            $("input[type=checkbox]").attr("disabled",true);

            var mEl = $(this);
            $('#order-content_' + $(this).attr('id') + ' input[type="checkbox"]').prop('checked', this.checked);
            me.settleSelect();
        });
        
        // 单个商品勾选
        $('.padd').delegate('input[name=item_checkbox]', 'click', function(){
        	me.settleSelect();
        });
        
        // 勾选所有
        $('.padd').delegate('input[name=all_checkbox]', 'click', function(){
        	$('.padd input[type="checkbox"]').prop('checked', this.checked);
        	me.settleSelect();
        });
    }
}

$(function(){
//    this.doing = false;
    cartObj.initListener();
//    alert(this.doing);
});


function addMyFavorite(shopcartId, goodsId) {
    layer.confirm('移入收藏后该商品将不在购物车中显示', {icon: 3, title:'提示',skin:'exit',area:['320px','200px']}, function(index) {
        $.post(ctx + "/shopcart/addMyFavorite", {
            shopcartId : shopcartId,
            goodsId : goodsId
        }, function(data) {
        	data = JSON.parse(data);
            if (data.success) {
                layer.msg(data.msg, {
                    icon : 1,
                    time : 1000
                //2秒关闭（如果不配置，默认是3秒）
                }, function() {
                    location.href = ctx + '/shopcart/shopcartList';
                });
            } else {
                layer.msg(data.msg, {
                    icon : 2,
                    time : 1000
                //2秒关闭（如果不配置，默认是3秒）
                });
            }
        });
        layer.close(index);
    });
}
function deleteShopcart(id) {
    layer.confirm('确认删除?', {icon: 3, title:'提示',skin:'exit',area:['320px','200px']}, function(index) {
        $.post(ctx + "/shopcart/delete", {
            id : id
        }, function(data) {
        	data = JSON.parse(data);
            if (data.success) {
                layer.msg(data.msg, {
                    icon : 1,
                    time : 1000
                //2秒关闭（如果不配置，默认是3秒）
                }, function() {
                    location.href = ctx + '/shopcart/shopcartList';
                });
            } else {
                layer.msg(data.msg, {
                    icon : 2,
                    time : 1000
                //2秒关闭（如果不配置，默认是3秒）
                });
            }
        });
        layer.close(index);
    });
}

//全选和反选
function selectShop(target) {
    var id = target.id;
    $('#shop_' + id + ' input[type="checkbox"]').prop('checked', target.checked);
}


// 选择或取消选中当前记录
function selectOne(target) {
    if (target.checked) {
//        $("#" + target.id).attr("checked", true);
//        $(target).parents("tr").children().each(function () {
//            $(this).css("background", "#D3F0F1");
//        });
    } else {
//        $("#" + target.id).attr("checked", false);
//        $("#motorInfo" + id).attr("checked", false);
//        $(target).parents("tr").children().each(function () {
//            $(this).css("background", "");
//        });
    }
}

function getCoupons(title, url){
	layer.open({
		type: 2,
		title: title,
		content: url,
		skin: "house-add",
		area: ["400px","300px"]
	});
}


